package org.cafeanimal.sqlite;

import com.google.common.base.Optional;


/**
 * Represents a table field.
 *
 * @author michael
 */
public class Field {
    private final String name;
    private final FieldType type;
    private final boolean primaryKey;

    public Field(String name, FieldType type, boolean primaryKey) {
        this.name = name;
        this.type = type;
        this.primaryKey = primaryKey;
    }

    public String getName() {
        return name;
    }

    public FieldType getType() {
        return type;
    }
    
    public boolean isPrimaryKey() {
        return primaryKey;
    }

    public boolean isCompatibleType(Object value) {
        Class<? extends Object> valueClass = value.getClass();
        Optional<FieldType> op = FieldType.getFieldType(valueClass);
        
        boolean ok = false;
        if (op.isPresent()) {
            ok = op.get().equals(this.type);
            
            // Check for allowable differences
            if (!ok) {
                if (Number.class.isAssignableFrom(valueClass) && this.type == FieldType.REAL) {
                    ok = true;
                }
            }
        }
        
        return ok;
    }

}
